﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.IO;
using System.Xml.Serialization;
using System.Xml;

namespace CustomTypes.Mono.Serializers
{

    /// <summary>
    /// Fonctions for work with Xml Serialize
    /// </summary>
    internal static class Serializer
    {

        /// <summary>
        /// Serialize an object of T type in XML, this method is an extension method to be used by referencing the <see cref="Mangas.Core.Serializers"/> namespace.
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="obj"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly")]
        public static string SerializeXml<T>(this T obj)
        {
            string result;

            using (MemoryStream fs = new MemoryStream())
            {
                using (XmlTextWriter w = new XmlTextWriter(fs, new UTF8Encoding()))
                {
                    XmlSerializer x = new XmlSerializer(typeof(T));
                    w.Formatting = Formatting.None;
                    x.Serialize(w, obj);
                    fs.Position = 0;
                    byte[] buffer = new byte[((int)fs.Length) + 1];
                    fs.Read(buffer, 0, (int)fs.Length);
                    result = Convert.ToBase64String(buffer, Base64FormattingOptions.None);

                }
            }

            return result;
        }

        /// <summary>
        /// Unserialize T
        /// </summary>
        /// <typeparam name="T"></typeparam>
        /// <param name="strdata"></param>
        /// <returns></returns>
        [System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Naming", "CA1709:IdentifiersShouldBeCasedCorrectly", MessageId = "Un"), System.Diagnostics.CodeAnalysis.SuppressMessage("Microsoft.Usage", "CA1816:CallGCSuppressFinalizeCorrectly")]
        public static object UnSerializeXml(this string strdata, Type type)
        {
            object result;

            byte[] buffer = Convert.FromBase64String(strdata);

            using (MemoryStream mem = new MemoryStream(buffer))
            {
                using (XmlTextReader r = new XmlTextReader(mem))
                {
                    XmlSerializer x = new XmlSerializer(type);
                    result = x.Deserialize(r);
                }
            }

            return result;

        }

   
    }



}
